import { RestHttpClient } from "../../../http";
import { detectToken } from "../../../token";
import { GetProductsTask } from "../task/products";

export class ProductsTraits {
    constructor(instance, trait_name = "private_products") {
        return {
            _data() {
                var ret = {};
                ret[trait_name] = {};
                ret[trait_name].response = [];

                ret[trait_name].private_onLoad = function () {
                    var options = ret[trait_name].response.data || [];
                    if (options) {
                        options = options.map(function (option, key) {
                            option.label = option.product_name;
                            option.value = option.hash;
                            option.selected = false;
                            return option;
                        });
                    }
                    if (ret[trait_name].onLoad) {
                        ret[trait_name].onLoad(options);
                    }
                };
                ret[trait_name].init = function () {
                    ret[trait_name].httpClient = new RestHttpClient();
                    ret[trait_name].httpClient.onLoad = function (...jsons) {
                        var response = [];
                        if (jsons[0]) {
                            ret[trait_name].response = jsons[0];
                            ret[trait_name].private_onLoad();
                        }
                    };

                    ret[trait_name].httpTask = new GetProductsTask();
                    ret[trait_name].httpClient.register(ret[trait_name].httpTask);
                };

                ret[trait_name].send = function (params) {
                    var self = this;
                    if (ret[trait_name].response.length < 1) {
                        detectToken()
                            .then(function (data) {
                                var sendParams = Object.assign({
                                    token: data.token
                                }, params);
                                ret[trait_name].httpTask.setParams(sendParams);
                                ret[trait_name].httpClient.send();
                            })
                            .catch(function (error) {
                            })
                    } else {
                        ret[trait_name].private_onLoad();
                    }
                };

                return ret;
            },
            _methods() {
                var methods = {};
                return methods;
            }
        }
    }
}